<!-- 账单抵扣 -->
<template>
	<a-modal v-bind="options" title="账单抵扣" class="bill-deduction-dialog">
		<div class="bill-deduction">
			<p v-color="{color: 'default'}" class="bill-deduction-title">
				可抵扣的金额为:
				<span v-color="{color: 'primary'}">&nbsp;{{ total.toFixed(2) }}</span>
				元
			</p>
		</div>
		<div class="grid">
			<a-typography-text strong>
				<blockquote>选择抵扣合同</blockquote>
			</a-typography-text>
			<vxe-grid ref="grid" v-bind="gridOptions" :data="tableData">
				<template #type="{row}">
					{{ row.houseAddress }}
				</template>
				<template #people="{row}">
					{{ row.name }}
					<span v-if="row.phone">/</span>
					{{ row.phone }}
				</template>
				<template #occupancy="{row}">
					<div>
						{{ row.beginTime }}
						<span v-if="row.EndTime">至</span>
						{{ row.endTime }}
					</div>
					<div>
						租金{{ row.price }}元/月&nbsp; 押金{{ row.deposit }}元&nbsp; 押{{ row.depositMonth }}
						<span v-show="row.periodMonth !== 99">付</span>
						{{ row.periodMonth === 99 ? `${payMany[row.periodMonth]}` : `${row.periodMonth}` }}
					</div>
				</template>
				<template #money="{row}">
					{{ row.receivableAmount.toFixed(2) }}
					<span>元 /</span>
					{{ row.deductionAmount.toFixed(2) }}元
				</template>
				<template #status="{row, rowIndex}">
					<a v-if="row.isDeduction">
						<a v-if="row.disabled && (row.approvalStatus === -1 || row.approvalStatus === 3)" @click="deduction(row, rowIndex)">
							抵扣
						</a>
						<a v-else>---</a>
					</a>
					<a v-else>
						<a @click="showDetails = true">详情</a>
						<a-divider v-if="true" type="vertical" />
						<a @click="cancel(row)">取消抵扣</a>
					</a>
				</template>
			</vxe-grid>
		</div>
		<template #footer>
			<a-button @click="emits('update:visible', false)">上一步</a-button>
			<a-button :loading="loading" type="primary" @click="save">确定</a-button>
		</template>
	</a-modal>
	<deduction-details v-model:visible="showDetails" :data="deductionData"></deduction-details>
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, watch, onMounted} from 'vue'
	import {VxeGridProps} from 'vxe-table'
	import {pagerConfig, proxyConfigProps} from 'yuxin-base/src/utils/vxe-table'
	import dayjs, {Dayjs} from 'dayjs'
	import {COLOR_MAP} from 'yuxin-base/src/directives/color'
	import DeductionDetails from '@/components/contract/contract-detail-dialog/charter-contract/deduction-details.vue'
	import {billDeductionList} from '@/api/charter-contract'
	import {payMany} from '@/utils/charter-contract'
	import {message} from 'ant-design-vue'
	import {singleRoomReturn} from '@/api/charter-contract'
	import {tenantBreakNormal, break_settle} from '@/api/contract'

	const emits = defineEmits(['update:visible', 'close', 'cancel'])

	const props = defineProps<{
		visible: boolean
		id: string
		enterPriseContractId: string
		totalMoney: number
		data: any
		modelRef: any
		rentingOutType?: any
	}>()
	const loading = ref(false)
	const deductionTargets = ref<any>([])
	const deductionData = ref<any>({
		contractId: '',
		deductionAmount: ''
	})

	const tableData = ref<any>([])

	const showDetails = ref(false)

	const params = reactive<any>({
		approvalStatus: 0,
		approvalStatusList: [],
		areaId: '',
		backRent: true,
		backRentRemind: 0,
		beginDateEnd: '',
		beginDateStart: '',
		cityId: '',
		contractMedium: 0,
		contractStatus: 0,
		contractStatusList: [],
		createBeginTime: '',
		createEndTime: '',
		createTime: '',
		current: 0,
		endDateEnd: '',
		endDateStart: '',
		enterPriseContractId: '',
		childrenContractId: '',
		enterPriseId: '',
		houseId: '',
		houseIds: [],
		housePid: '',
		ids: [],
		isSearchCount: 0,
		keyId: '',
		label: 0,
		like: '',
		matchType: 0,
		order: '',
		quitDateEnd: '',
		quitDateStart: '',
		signBeginTime: '',
		signDeptId: '',
		signEmpId: '',
		signEndTime: '',
		signProgress: 0,
		signType: 0,
		size: 0,
		sort: '',
		tenantId: '',
		townId: '',
		updateTime: ''
	})

	const options = reactive({
		width: 1100,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		},
		onOk() {}
	})

	const gridOptions = reactive<VxeGridProps>({
		height: '400',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '房源地址',
				minWidth: 350,
				slots: {
					default: 'type'
				}
			},
			// {
			// 	title: '入住人姓名/电话',
			// 	minWidth: 300,
			// 	slots: {
			// 		default: 'people'
			// 	}
			// },
			{
				title: '周期/租金/押金/付款方式',
				minWidth: 350,
				slots: {
					default: 'occupancy'
				}
			},
			{
				title: '应收/抵扣金额',
				minWidth: 200,
				slots: {
					default: 'money'
				}
			},
			{
				title: '操作',
				align: 'center',
				minWidth: 150,
				fixed: 'right',
				slots: {
					default: 'status'
				}
			}
		]
	})

	const total = ref(0)
	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				params.enterPriseContractId = props.enterPriseContractId
				params.childrenContractId = props.id
				billDeductionList(params).then((res: any) => {
					tableData.value = res.data.map((e: any) => {
						e.deductionAmount = 0
						e.isDeduction = true
						if (total.value > 0) {
							e.disabled = true
						} else {
							e.disabled = false
						}

						return e
					})
				})
				total.value = Math.abs(props.totalMoney)
			} else {
				total.value = 0
			}
		}
	)

	const grid = ref()

	const getList = (page?: any) => {
		grid.value.commitProxy(page === 1 ? 'reload' : 'query')
	}
	const deduction = (data: any, index: number) => {
		data.isDeduction = false
		if (Math.abs(data.receivableAmount) >= Math.abs(total.value)) {
			data.deductionAmount = total.value
			total.value = 0
		} else {
			data.deductionAmount = data.receivableAmount
			total.value = Math.abs(total.value) - Math.abs(data.receivableAmount)
			// total.value = total.value.toFixed(2)
		}
		if (Math.abs(total.value) === 0) {
			tableData.value = tableData.value.map((e: any) => {
				e.disabled = false
				return e
			})
			tableData.value[index].disabled = true
		}
		deductionData.value.contractId = data.contractId
		deductionData.value.deductionAmount = data.deductionAmount
		deductionData.value.houseAddress = data.houseAddress
	}
	const cancel = (data: any) => {
		console.log(total.value)

		data.isDeduction = true
		total.value = Number(total.value) + Number(data.deductionAmount)
		data.deductionAmount = 0

		if (Math.abs(total.value) !== 0) {
			tableData.value = tableData.value.map((e: any) => {
				e.disabled = true
				return e
			})
		}
	}
	const save = () => {
		const isClick = tableData.value.every((e: any) => e.isDeduction)
		if (total.value !== 0 && tableData.value.length > 0 && isClick) {
			message.error('请先选择抵扣合同进行抵扣')
		} else {
			loading.value = true
			tableData.value.forEach((e: any) => {
				if (!e.isDeduction) {
					if (e.deductionAmount > 0) {
						deductionTargets.value.push({
							bizId: e.contractId,
							deductionAmount: e.deductionAmount
						})
					} else {
						deductionTargets.value.push({
							bizId: e.contractId,
							deductionAmount: 0
						})
					}
				}
			})
			const rentingOut = {
				backType: props.modelRef.normal,
				contractId: props.id,
				houseId: props.modelRef.houseId,
				finances: props.data,
				quiteComment: props.modelRef.quiteComment,
				quiteDate: props.modelRef.quiteDate,
				paymentAccountType: props.modelRef.paymentAccountType,
				paymentAccount: props.modelRef.paymentAccount,
				deductionTargets: deductionTargets.value,
				bankNumber: props.modelRef.bankNumber,
				bankName: props.modelRef.bankName,
				isBreakNotCalc: props.rentingOutType === 'settlement' ? true : false
			}
			if (props.modelRef.deliveryAddForm) {
				rentingOut['deliveryAddForm'] = props.modelRef.deliveryAddForm
			}
			// console.log(props.modelRef)
			// props.modelRef.normal? tenantBreakNormal(params) : tenantBreakAbNormal(params)
			// if (total.value === 0) {

			// 结算 走 结算接口
			if (props.rentingOutType === 'settlement') {
				break_settle(rentingOut).finally(() => {
					success()
				})
				return
			}

			if (props.modelRef.normal === 1 && dayjs().isBefore(props.modelRef.quiteDate, 'day')) {
				loading.value = false
				return message.error('合同未到期，无法办理到期退')
			}

			if (props.modelRef.normal === 1) {
				tenantBreakNormal(rentingOut).finally(() => {
					success()
				})
			}

			// 违约退 todo
			if (props.modelRef.normal === 2) {
				singleRoomReturn(rentingOut).finally(() => {
					success()
				})
			}

			// } else {
			// 	message.error('请抵扣')
			// }·
		}
	}

	const success = () => {
		emits('update:visible', false)
		emits('cancel')
		loading.value = false
	}
</script>

<style lang="less">
	.bill-deduction-dialog {
		.ant-modal-body {
			padding: 0;
		}
		.bill-deduction-title {
			font-size: 14px;
			padding: 10px 24px;
			line-height: 20px;
		}
		.grid {
			padding: 0 24px;
		}
		.bill-deduction {
			width: 100%;
			height: 40px;
			background-color: #f5f9ff;
			border-radius: 0px 0px 0px 0px;
		}
	}
</style>
